﻿function encodeHTML(str) {
    return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function decodeHTML(str) {
    return str.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
}

function loadCategories(storeID) {
    $.ajax({
        type: "GET",
        data: "storeID=" + storeID,
        url: "/intranet/TopmenuGetCategories",
        success: function (msg) {
            $("#CategoryList").html(msg);
            $("#categories-list-ul").sortable({ item: "li" });
        }
    });
}

function topCatCheckBoxChange(catID) {
    if ($("#cat-" + catID).is(":checked")) {
        $("#cat-" + catID).parent("li").insertAfter("#categories-list-ul .selectedTopCat:last");
        $("#cat-" + catID).parent("li").addClass("selectedTopCat");
        $("#cat-" + catID).parent("li").append("<input id='display-" + catID + "' class='displayTextBox' value='' type='text' />");
    } else {
        $("#cat-" + catID).parent("li").removeClass("selectedTopCat");
        $("#display-" + catID).remove();
    }
}

$(document).ready(function () {
    loadCategories($("#store-dropdown").val());
    // When user change the store
    $("#store-dropdown").change(function () {
        loadCategories($("#store-dropdown").val());
    });
    // When user reload the category
    $("#Reload-Category").click(function () {
        loadCategories($("#store-dropdown").val());
    });
    // When user click update button, it will save the information into the database using AJAX
    $("#Update-Category").click(function () {
        var selectedCatList = "";
        // Get the list of Checked Category ID
        $("#categories-list-ul input[type=checkbox]:checked").each(function () {
            thisId = $(this).attr("id").replace("cat-", "");
            selectedCatList += "|" + thisId + "¬" + encodeHTML($("#display-" + thisId).val());
        });
        selectedCatList = encodeURIComponent(selectedCatList.substr(1, selectedCatList.length - 1)); // Remove the first |
        // Send out the ajax
        $.ajax({
            type: "POST",
            data: "storeID=" + $("#store-dropdown").val() + "&catList=" + selectedCatList,
            url: "/intranet/UpdateTopMenuCategories",
            success: function (msg) {
                alert("Update successfully");
                // relead the list when complete
                loadCategories($("#store-dropdown").val());
            },
            fail: function (msg) {
                alert("Sorry, Update process's failed. Please try again later");
            }
        });
    });
});